﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CommonLibrary.Interfaces.ImageCapture;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace CommonLibrary.Classes.ImageCapture
{
    public class ByteArrayCapture : IImageCapture<byte[]>
    {
        private Graphics _screenImage;
        private ImageFormat _screenImageFormat;
        private Bitmap _screenBitMap;

        public Graphics ScreenImage
        {
            get
            {
                return _screenImage;
            }
           
        }

        public ImageFormat ScreenImageFormat
        {
            get
            {
                return _screenImageFormat;
            }
           
        }

        public Bitmap ScreenBitMap
        {
            get
            {
                return _screenBitMap;
            }
           
        }

        public bool CaptureImage(byte[] capture)
        {
            bool valid = true;

            try
            {
                MemoryStream memStream = new MemoryStream(capture);
                Image returnImage = Image.FromStream(memStream);

                _screenBitMap = new Bitmap(returnImage);
                if (_screenImageFormat == null)
                {
                    _screenImageFormat = ImageFormat.Png;
                }
            }
            catch (Exception error)
            {
                valid = false;
                throw new InvalidOperationException("Unable to capture image", error);
            }


            return valid;
        }

        public bool SaveImage(string pathWithFileName)
        {
            bool valid = true;
            try
            {
                _screenBitMap.Save(pathWithFileName, _screenImageFormat);
            }
            catch (Exception error)
            {
                valid = false;
                throw new InvalidOperationException("Unable to save the image to the specified location", error);
            }

            return valid;
        }

        public byte[] ConvertToByteArray()
        {
            byte[] returnArray = null;

            try
            {
                MemoryStream imageMemStream = new MemoryStream();
                _screenBitMap.Save(imageMemStream, _screenImageFormat);
                returnArray = imageMemStream.ToArray();
            }
            catch (Exception error)
            {
                throw new InvalidCastException("Unable to convert image in byte array", error);
            }


            return returnArray;
        }
    }
}
